// pages/reviewRecord/listenWorld/listenWorld.js
const app = getApp();
// let tool = require('../../../utils/tool.js');
const httpUtils = require('../../../utils/httpUtils.js');
let util = require('../../../utils/util.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasSel: {},
    percent: 0,
    totalNum: 0,
    imageUrl: app.globalData.imageurl,
    gameSecond: 15,
    worldList: {},
    curIndex: 0,
    innerAudioContext: new Object(),
    timer: '',
    wordID: 0,
    wordLen: 0,
    wordCur: {},
    listDatas: {},
    allWord: '',
    errWord: '',
    errNum: 0,
    canClick: 0,
    ishide: "1",
    date: "", //学习日期
    sort: '3', //作业形式 1 词义闯关 2 对对碰 3 廷议释义 4 组合拼 5读一遍 6 写一遍   0 学后检测
    task_id: '', //任务id
    maskDis: 'none',
    ggDis: 'none',
    gfDis: 'none',
    isNextPassFlag: false,
  },

  //倒计时
  daojishi: function () {
    let that = this;
    that.data.timer = setInterval(function () {
      let num = parseInt(that.data.gameSecond) - 1;
      let cid = that.data.curIndex + 1;
      if (num < 10 && num >= 0) {
        num = "0" + num.toString();
      }
      that.setData({
        gameSecond: num,
        curIndex: cid,
      });

      if (parseInt(that.data.gameSecond) <= 0) {
        that.addErrWord(that.data.wordCur.word);
        if (that.data.wordID < (that.data.wordLen - 1)) {
          that.playNext();
        } else {
          clearInterval(that.data.timer);
          // that.submitAnswer();
          console.log("倒计时时长到，弹窗")
          that.calculateWrong();
          let errNum = that.data.errNum;
          let allNum = that.data.wordLen;
          if (errNum > parseInt(allNum / 2)) {
            //  错词大于一半为不过关
            that.setData({
              gfDis: 'flex',
              ggDis:'none',
              maskDis: 'flex',
            });
          } else {
            that.setData({
              ggDis: 'flex',
              gfDis:'none',
              maskDis: 'flex'
            });
          }
        }

      }
    }, 1000);
	console.log('____________________')
	console.log(that.data.timer)
	console.log('____________________')
  },
  playNext: function () {
    this.data.innerAudioContext.stop();
    this.setData({
      allWord: this.data.allWord + "," + this.data.listDatas[(this.data.wordID + 1)].word,
      wordCur: this.data.listDatas[(this.data.wordID + 1)],
      wordID: (this.data.wordID + 1),
      curIndex: 0,
      percent: parseInt(100 / this.data.wordLen * (this.data.wordID + 2)),
      gameSecond: 15,
      hasSel: {},
      canClick: 0
    });

    this.playMp3(this.data.wordCur.vedio_url);
  },
  addErrWord: function (errData) {
    let temWrod = this.data.errWord;
    if (temWrod === "") {
      temWrod = errData;
    } else {
      temWrod = temWrod + "," + errData;
    }
    this.setData({
      errWord: temWrod
    })
  },

  // 计算错词 
  calculateWrong() {
    let that = this;
    if (that.data.errWord) {
      let errWords= that.data.errWord.split(",");
      let errorlist = Array.from(new Set(errWords));
      let wordlen = that.data.wordLen;
      let errnum = errorlist.length > wordlen ? wordlen : errorlist.length;
      that.setData({
        errNum: errnum
      })
    }
  },

  //提交答案
  submitAnswer: function () {
    let that = this;
    console.log("调提交答案接口,错词" + that.data.errNum)
    console.log("allword="+that.data.allWord)
    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.submitWordReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
      sort: that.data.sort,
      pic: "",
      stu_answer: "",
      errword: that.data.errWord,
      allword: that.data.allWord,
    }).then((res) => {
      wx.hideLoading();
      let remainword = res.data.remain;
      if (remainword <= 0) {
        console.log("剩余单词数小于等于0了，提交完成直接跳报告页")
        setTimeout(function () {
          wx.showToast({
            title: "恭喜你完成复习~",
            icon: 'none',
            duration: 2000
          });
        }, 500)
        wx.redirectTo({
          url: '../playReport/playReport?task_id=' + that.data.task_id + "&sort=" + that.data.sort + "&can_submit=" + that.data.can_submit + "&date=" + that.data.date + "&type=0",
        })
        return;
      }
      console.log("提交成功~isNextPassFlag=" + that.data.isNextPassFlag)
      if (that.data.isNextPassFlag) {
        console.log("获取下一关的数据")
        //初始化数据
        that.initData();
        //获取下一关的数据
        that.getData();
      }else{
        console.log("点不想玩了，提交成功，跳转报告页")
        wx.redirectTo({
          url: '../playReport/playReport?task_id=' + that.data.task_id + "&sort=" + that.data.sort + "&can_submit=" + that.data.can_submit + "&date=" + that.data.date + "&type=0",
        })
      }
    });

  },


  //初始化数据
  initData() {
    let that = this;
    that.setData({
      maskDis: 'none',
      ggDis: 'none',
      gfDis: 'none',
      gameSecond: 15,
      curIndex: 0,
      errWord: '',
      canClick: 0,
      errNum: 0,
      wordID: 0,
      hasSel: {},
    })
  },

  //下一关
  nextPass:util.throttle(function(){
    let that = this;
    //先提交本关
    console.log("错词" + that.data.errNum + "个，点击了下一关")
    that.setData({
      isNextPassFlag: true
    })
    that.submitAnswer();
    clearInterval(that.data.timer);
    //初始化数据
    // that.initData();
    //获取下一关的数据
    // that.getData();
  },1500),

  toReport:util.throttle(function(){
    let that = this;
    that.setData({
      isNextPassFlag: false
    })
    that.submitAnswer();
  
  },1500),


  //重玩本关
  replay:util.throttle(function(){
    let that = this;
    let list = that.data.listDatas;
    console.log("之前的allword="+that.data.allWord);
    clearInterval(that.data.timer);
    //初始化数据
    that.setData({
      maskDis: 'none',
      ggDis: 'none',
      gfDis: 'none',
      gameSecond: 15,
      curIndex: 0,
      allWord: list[0].word,
      errWord: '',
      canClick: 0,
      errNum: 0,
      percent: parseInt(100 / list.length * 1),
      wordID: 0,
      wordCur: list[0],
      hasSel: {},
      isNextPassFlag: false
    })
    that.daojishi();
    that.playMp3(that.data.wordCur.vedio_url);
  },1500),


  clickTxt: function (e) {
    let that = this;
    if (this.data.canClick === 1) {
      return;
    }
    let temID = e.currentTarget.dataset.index;
    let temArr = {};
    temArr[this.data.wordCur.right] = 'v1-1-ok';
    if (temID == this.data.wordCur.right) {
      this.playMp3(app.globalData.mp3.gamesuccess);
    } else {
      this.addErrWord(this.data.wordCur.word)
      temArr[temID] = 'v1-1-err';
      this.playMp3(app.globalData.mp3.selectwrong);
    }
    this.setData({
      hasSel: temArr,
      canClick: 1
    })
    if (this.data.wordID >= (this.data.wordLen - 1)) {

      clearInterval(this.data.timer);
      // this.submitAnswer();
      that.calculateWrong();
      let errNum = that.data.errNum;
      let allNum = that.data.wordLen;
      if (errNum > parseInt(allNum / 2)) {
        //  错词大于一半为不过关
        that.setData({
          gfDis: 'flex',
          ggDis:'none',
          maskDis: 'flex',
          canClick: 1
        });
      } else {
        that.setData({
          ggDis: 'flex',
          gfDis:'none',
          maskDis: 'flex',
          canClick: 1
        });
      }

    } else {
      let that = this;
      setTimeout(function () {
        that.playNext()
      }, 1000);
    }


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //获取传过来的日期
    that.setData({
      task_id: options.task_id,
      date: options.date,
      can_submit: options.can_submit
    })
    console.log(that.data.date)
    this.data.innerAudioContext = wx.createInnerAudioContext()
    this.data.innerAudioContext.autoplay = false;
    this.data.innerAudioContext.loop = false;
    this.getData();

  },
  playMp3: function (url) {
    this.data.innerAudioContext.src = url;
    this.data.innerAudioContext.play();
  },
  playOne: function () {
    this.playMp3(this.data.wordCur.vedio_url);
  },



  //获取数据
  getData: function () {
    var that = this;
    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.getWordListenReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.task_id,
    }).then((res) => {
      wx.hideLoading();
      let list = res.data;
      if (list.length < 1) {
        console.log("获取数据，已无数据跳转报告页")
        wx.redirectTo({
          url: '../playReport/playReport?task_id=' + that.data.task_id + "&sort=" + that.data.sort + "&can_submit=" + that.data.can_submit + "&date=" + that.data.date + "&type=0",
        })
        return;
      }


      that.setData({
        totalNum: res.data.length,
        listDatas: res.data,
        wordLen: res.data.length,
        wordCur: list[0],
        allWord: list[0].word,
        percent: parseInt(100 / res.data.length * 1)
      });

      that.daojishi();
      that.playMp3(that.data.wordCur.vedio_url);
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.ishide == 2) {
      this.setData({
        ishide: 1
      })
      this.daojishi();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('listen hide')
    this.setData({
      ishide: 2
    })
    clearInterval(this.data.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('listen onUnload')
    clearInterval(this.data.timer);
    this.data.innerAudioContext.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})